import {getDocument} from 'pdfjs-dist'
const Canvas = require("canvas")

const assert = require("assert").strict
const fs = require("fs")
class NodeCanvasFactory {
  create(width, height) {
    assert(width > 0 && height > 0, "Invalid canvas size")
    const canvas = Canvas.createCanvas(width, height)
    const context = canvas.getContext("2d")
    return {
      canvas,
      context,
    }
  }
  reset(canvasAndContext, width, height) {
    assert(canvasAndContext.canvas, "Canvas is not specified")
    assert(width > 0 && height > 0, "Invalid canvas size")
    canvasAndContext.canvas.width = width
    canvasAndContext.canvas.height = height
  }
  destroy(canvasAndContext) {
    assert(canvasAndContext.canvas, "Canvas is not specified")

    // Zeroing the width and height cause Firefox to release graphics
    // resources immediately, which can greatly reduce memory consumption.
    canvasAndContext.canvas.width = 0
    canvasAndContext.canvas.height = 0
    canvasAndContext.canvas = null
    canvasAndContext.context = null
  }
}

// const pdfjsLib = require("pdfjs-dist/es5/build/pdf.js")


// Some PDFs need external cmaps.
const CMAP_URL = "./node_modules/pdfjs-dist/cmaps/"
const CMAP_PACKED = true
const defaultPdfPath = "未命名1_加水印.pdf"
const pdfToImage = async (pdfPath, pageNumber = 1) => {
  // Loading file from file system into typed array.
  const data = new Uint8Array(fs.readFileSync(pdfPath))
  // Load the PDF file.
  const loadingTask = getDocument({
    data,
    cMapUrl: CMAP_URL,
    cMapPacked: CMAP_PACKED,
  })
  const doc = await loadingTask.promise
  const page = await doc.getPage(pageNumber)
  const viewport = page.getViewport({ scale: 4.0 })
  const canvasFactory = new NodeCanvasFactory()
  const canvasAndContext = canvasFactory.create(viewport.width, viewport.height)
  const renderContext = {
    canvasContext: canvasAndContext.context,
    viewport,
    canvasFactory,
  }
  const renderTask = page.render(renderContext)
  await renderTask.promise
  const image = canvasAndContext.canvas.toBuffer()
  fs.writeFile("output4.png", image, function(error) {
    if (error) {
      console.error("Error: " + error)
    } else {
      console.log("Finished converting first page of PDF file to a PNG image.")
    }
  })
}


function main() {
  pdfToImage(defaultPdfPath)
}
export {
  main
}
